<template>
  <div class="product-allocation-container">
    <!-- 筛选与预警配置区域 -->
    <el-card class="filter-container">
      <el-form ref="queryForm" :inline="true" :model="queryParams">
        <el-form-item label="商品名称">
          <el-input v-model="queryParams.productName" maxlength="40" placeholder="请输入商品名称" show-word-limit />
        </el-form-item>
        <el-form-item label="采购单号">
          <el-input v-model="queryParams.purchaseOrderNo" placeholder="请输入采购单号" />
        </el-form-item>
        <el-form-item label="所在仓库">
          <el-select v-model="queryParams.warehouseId" filterable placeholder="请选择所在仓库">
            <el-option label="全部" value="" />
            <el-option v-for="item in warehouseOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="库存中" value="库存中" />
            <el-option label="部分出库" value="部分出库" />
            <el-option label="全部出库" value="全部出库" />
            <el-option label="已退货" value="已退货" />
            <el-option label="已调拨" value="已调拨" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">筛选</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button
          class="inventory-alert-btn"
          :disabled="isCheckingAlerts"
          type="warning"
          @click="showInventoryAlerts"
          >
            库存预警
            <el-badge v-if="inventoryAlertCount > 0" class="alert-badge" :value="inventoryAlertCount" />
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 库存预警配置内容 -->
      <div style="margin-top: 20px; border-top: 1px solid #ebeef5; padding-top: 20px;">
        <div style="font-weight: bold; margin-bottom: 15px; font-size: 16px;">库存预警配置</div>
        <el-form label-width="150px" :model="inventoryAlertConfig" size="small">
          <el-form-item label="低库存阈值">
            <el-input-number v-model="inventoryAlertConfig.lowStockThreshold" controls-position="right" :min="1" />
            <span style="margin-left: 10px; color: #909399;">(系统建议: {{ recommendedLowStockThreshold }})</span>
          </el-form-item>
          <el-form-item label="高库存阈值">
            <el-input-number v-model="inventoryAlertConfig.highStockThreshold" controls-position="right" :min="inventoryAlertConfig.lowStockThreshold + 1" />
            <span style="margin-left: 10px; color: #909399;">(系统建议: {{ recommendedHighStockThreshold }})</span>
          </el-form-item>
          <el-form-item label="平均消耗计算周期">
            <el-input-number v-model="inventoryAlertConfig.averageConsumptionPeriod"  controls-position="right" :min="1" /> 天
             <span style="margin-left: 10px; color: #909399;">(用于计算低库存建议阈值)</span>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="applyAndRecalculateAlerts">应用新阈值并检查</el-button>
            <el-button @click="recalculateRecommendations">刷新建议阈值</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-container" style="margin-top: 15px;">
      <div style="margin-bottom: 15px;">
        <el-button type="danger" @click="clearAllData">清空所有数据</el-button>
      </div>
      <el-table border :data="tableData" style="width: 100%">
        <el-table-column label="商品名称" prop="productName" width="150" />
        <el-table-column label="采购单号" prop="purchaseOrderNo" width="180" />
        <el-table-column label="物流单号" prop="logisticsNo" width="150" />
        <el-table-column label="所在仓库" prop="warehouseLabel" width="150" />
        <el-table-column label="初始数量" prop="initialQuantity" width="100" />
        <el-table-column label="当前数量" prop="currentQuantity" width="100" />
        <el-table-column label="入库时间" prop="storageTimestamp" width="180" />
        <el-table-column label="状态" prop="status" width="100" />
        <el-table-column fixed="right" label="操作" width="220">
          <template slot-scope="scope">
            <el-button size="small" type="text" @click="handleDispatch(scope.row)">出库</el-button>
            <el-button size="small" type="text" @click="handleReturn(scope.row)">退货</el-button>
            <el-button size="small" type="text" @click="handleTransfer(scope.row)">调拨</el-button>
            <el-button size="small" type="text" @click="handleDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        :current-page.sync="pagination.currentPage"
        layout="total, sizes, prev, pager, next, jumper"
        :page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </el-card>

    <!-- 出库弹窗 -->
    <el-dialog title="商品出库" :visible.sync="dispatchDialog.visible" width="500px" @closed="resetDispatchForm">
      <el-form ref="dispatchForm" label-width="100px" :model="dispatchDialog.form" :rules="dispatchDialog.rules">
        <el-form-item label="商品名称">
          <el-input disabled :value="dispatchDialog.currentRow ? dispatchDialog.currentRow.productName : ''" />
        </el-form-item>
        <el-form-item label="当前仓库">
          <el-input disabled :value="dispatchDialog.currentRow ? dispatchDialog.currentRow.warehouseLabel : ''" />
        </el-form-item>
        <el-form-item label="当前数量">
          <el-input disabled :value="dispatchDialog.currentRow ? dispatchDialog.currentRow.currentQuantity : ''" />
        </el-form-item>
        <el-form-item label="出库数量" prop="quantity">
          <el-input-number v-model="dispatchDialog.form.quantity" :max="dispatchDialog.currentRow ? dispatchDialog.currentRow.currentQuantity : 1" :min="1"/>
        </el-form-item>
        <el-form-item label="出库去向" prop="destination">
          <el-input v-model="dispatchDialog.form.destination" placeholder="例如：客户A，XX项目" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dispatchDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmDispatch">确认出库</el-button>
      </div>
    </el-dialog>

    <!-- 调拨弹窗 -->
     <el-dialog title="商品调拨" :visible.sync="transferDialog.visible" width="500px" @closed="resetTransferForm">
      <el-form ref="transferForm" label-width="100px" :model="transferDialog.form" :rules="transferDialog.rules">
        <el-form-item label="商品名称">
          <el-input disabled :value="transferDialog.currentRow ? transferDialog.currentRow.productName : ''" />
        </el-form-item>
        <el-form-item label="当前仓库">
          <el-input disabled :value="transferDialog.currentRow ? transferDialog.currentRow.warehouseLabel : ''" />
        </el-form-item>
         <el-form-item label="当前数量">
          <el-input disabled :value="transferDialog.currentRow ? transferDialog.currentRow.currentQuantity : ''"  />
        </el-form-item>
        <el-form-item label="调拨数量" prop="quantity">
          <el-input-number v-model="transferDialog.form.quantity" :max="transferDialog.currentRow ? transferDialog.currentRow.currentQuantity : 1" :min="1"/>
        </el-form-item>
        <el-form-item label="目标仓库" prop="targetWarehouseId">
          <el-select v-model="transferDialog.form.targetWarehouseId" filterable placeholder="请选择目标仓库">
            <el-option
              v-for="item in availableWarehouseOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="transferDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmTransfer">确认调拨</el-button>
      </div>
    </el-dialog>

    <!-- 退货弹窗 -->
    <el-dialog title="商品退货" :visible.sync="returnDialog.visible" width="500px">
      <el-form ref="returnForm" label-width="100px" :model="returnDialog.form" :rules="returnDialog.rules">
        <el-form-item label="商品名称">
          <el-input disabled :value="returnDialog.currentRow ? returnDialog.currentRow.productName : ''" />
        </el-form-item>
        <el-form-item label="当前仓库">
          <el-input disabled :value="returnDialog.currentRow ? returnDialog.currentRow.warehouseLabel : ''" />
        </el-form-item>
        <el-form-item label="当前数量">
          <el-input disabled :value="returnDialog.currentRow ? returnDialog.currentRow.currentQuantity : ''" />
        </el-form-item>
        <el-form-item label="退货原因" prop="reason">
          <el-input v-model="returnDialog.form.reason" placeholder="请输入退货原因" :rows="3" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="returnDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmReturn">确认退货</el-button>
      </div>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog title="商品详情" :visible.sync="detailDialog.visible" width="600px">
      <el-descriptions border :column="1">
        <el-descriptions-item label="商品名称">{{ detailDialog.currentRow ? detailDialog.currentRow.productName : '' }}</el-descriptions-item>
        <el-descriptions-item label="采购单号">{{ detailDialog.currentRow ? detailDialog.currentRow.purchaseOrderNo : '' }}</el-descriptions-item>
        <el-descriptions-item label="物流单号">{{ detailDialog.currentRow ? detailDialog.currentRow.logisticsNo : '' }}</el-descriptions-item>
        <el-descriptions-item label="所在仓库">{{ detailDialog.currentRow ? detailDialog.currentRow.warehouseLabel : '' }}</el-descriptions-item>
        <el-descriptions-item label="初始数量">{{ detailDialog.currentRow ? detailDialog.currentRow.initialQuantity : '' }}</el-descriptions-item>
        <el-descriptions-item label="当前数量">{{ detailDialog.currentRow ? detailDialog.currentRow.currentQuantity : '' }}</el-descriptions-item>
        <el-descriptions-item label="入库时间">{{ detailDialog.currentRow ? detailDialog.currentRow.storageTimestamp : '' }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ detailDialog.currentRow ? detailDialog.currentRow.status : '' }}</el-descriptions-item>
        <el-descriptions-item v-if="detailDialog.currentRow && detailDialog.currentRow.remarks" label="备注">
          {{ detailDialog.currentRow.remarks }}
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 库存预警弹窗 -->
    <el-dialog title="库存预警" :visible.sync="inventoryAlertDialog.visible" width="600px">
      <div v-if="inventoryAlertDialog.alerts.length > 0">
        <el-alert
          v-for="(alert, index) in inventoryAlertDialog.alerts"
          :key="index"
          class="inventory-alert-item"
          :closable="false"
          :description="alert.description"
          show-icon
          :title="alert.title"
          :type="alert.type"
        />

        <div class="inventory-alert-suggestion">
          <h4>智能建议</h4>
          <p>{{ inventoryAlertDialog.suggestion }}</p>
        </div>
      </div>
      <div v-else class="no-alerts-message">
        <i class="el-icon-success"></i>
        <p>当前没有库存预警</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="inventoryAlertDialog.visible = false">关闭</el-button>
        <el-button type="primary" @click="handleAlertAction">{{ inventoryAlertDialog.actionText }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ProductAllocation',
  data() {
    return {
      queryParams: {
        productName: '',
        purchaseOrderNo: '',
        warehouseId: '',
        status: '',
      },
      warehouseOptions: [], // 与采购管理页面保持一致或从全局状态/API获取
      originalTableData: [], // 从localStorage加载的原始数据
      tableData: [], // 当前页显示的数据
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      dispatchDialog: {
        visible: false,
        currentRow: null,
        form: {
          quantity: 1,
          destination: '',
        },
        rules: {
          quantity: [{ required: true, message: '请输入出库数量', trigger: 'blur' }],
          destination: [{ required: true, message: '请输入出库去向', trigger: 'blur' }],
        },
      },
      transferDialog: {
        visible: false,
        currentRow: null,
        form: {
          quantity: 1,
          targetWarehouseId: '',
        },
        rules: {
          quantity: [{ required: true, message: '请输入调拨数量', trigger: 'blur' }],
          targetWarehouseId: [{ required: true, message: '请选择目标仓库', trigger: 'change' }],
        },
      },
      returnDialog: {
        visible: false,
        currentRow: null,
        form: {
          reason: '',
        },
        rules: {
          reason: [{ required: true, message: '请输入退货原因', trigger: 'blur' }],
        },
      },
      detailDialog: {
        visible: false,
        currentRow: null,
      },
      // 新增库存预警相关数据
      inventoryAlertDialog: {
        visible: false,
        alerts: [],
        suggestion: '',
        actionText: '查看详情',
        actionType: 'view',
        targetWarehouse: null,
        targetProduct: null
      },
      // 库存预警配置
      inventoryAlertConfig: {
        lowStockThreshold: 10, // 低库存阈值 (将变为用户可配置)
        highStockThreshold: 1000, // 高库存阈值 (将变为用户可配置)
        daysToConsiderForTrend: 30, // 趋势分析的天数
        averageConsumptionPeriod: 7, // 平均消耗计算周期（天）
        enableSmartPrediction: true, // 是否启用智能预测
      },
      // 新增：推荐阈值
      recommendedLowStockThreshold: 10,
      recommendedHighStockThreshold: 1000,
      // 新增预警状态变量
      inventoryAlertCount: 0,
      isCheckingAlerts: false,
      lastAlertCheckTime: null
    }
  },
  computed: {
    availableWarehouseOptions() {
      if (!this.transferDialog.currentRow) return this.warehouseOptions;
      // 调拨时，目标仓库不能是当前仓库
      return this.warehouseOptions.filter(wh => wh.value !== this.transferDialog.currentRow.warehouseId);
    }
  },
  created() {
    this.loadAllocationData()
    this.loadWarehouseOptions() // 添加这一行，初始化时加载仓库数据
    this.calculateRecommendedThresholds() // 初始化时计算推荐阈值
  },
  mounted() {
    // 监听采购页面更新localStorage的事件
    window.addEventListener('storageUpdated', this.handleStorageUpdate);
    // 也监听标准的storage事件，以防万一
    window.addEventListener('storage', this.handleDefaultStorageUpdate);

    // 初始检查库存预警数量，但不显示弹窗
    this.$nextTick(() => {
      this.checkInventoryAlertsCount();
      this.calculateRecommendedThresholds(); // 也在此处计算一次，确保数据加载后更新
    });
  },
  beforeDestroy() {
    window.removeEventListener('storageUpdated', this.handleStorageUpdate);
    window.removeEventListener('storage', this.handleDefaultStorageUpdate);
  },
  methods: {
    clearAllData() {
      this.$confirm('此操作将清空所有商品调拨数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 清空数据
        this.originalTableData = [];
        this.tableData = [];
        this.pagination.total = 0;

        // 清空localStorage
        localStorage.removeItem('productAllocationData');

        // 触发事件，通知其他页面更新
        window.dispatchEvent(new CustomEvent('storageUpdated', { detail: { key: 'productAllocationData' } }));

        // 更新库存预警数量
        this.inventoryAlertCount = 0;
        localStorage.setItem('inventoryAlertCount', '0');

        // 通知首页更新库存预警数量
        window.dispatchEvent(new CustomEvent('storageUpdated', { detail: { key: 'inventoryAlertCount' } }));

        this.$message({
          type: 'success',
          message: '数据已清空'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消清空操作'
        });
      });
    },
    handleStorageUpdate(e) {
      if (e.detail && e.detail.key === 'productAllocationData') {
        this.loadAllocationData();
      } else if (e.detail && e.detail.key === 'warehouseTableData') {
        this.loadWarehouseOptions();
      }
    },
    handleDefaultStorageUpdate(e) {
       if (e.key === 'productAllocationData') {
        this.loadAllocationData();
      } else if (e.key === 'warehouseTableData') {
        this.loadWarehouseOptions();
      }
    },
    loadWarehouseOptions() {
      const warehouseData = localStorage.getItem('warehouseTableData')
      if (warehouseData) {
        const warehouses = JSON.parse(warehouseData)
        this.warehouseOptions = warehouses.map(warehouse => ({
          value: `WH_${warehouse.id}`,
          label: warehouse.name
        }))
      } else {
        // 如果没有数据，使用默认值
        this.warehouseOptions = [
          { value: 'WH_001', label: '北京中心仓' },
          { value: 'WH_002', label: '上海配送中心' },
          { value: 'WH_003', label: '广州物流仓' },
          { value: 'WH_004', label: '深圳分仓' },
        ]
      }
    },
    loadAllocationData() {
      const data = localStorage.getItem('productAllocationData')
      this.originalTableData = data ? JSON.parse(data) : []
      this.handleQuery()

      // 加载完数据后检查库存预警数量，但不显示弹窗
      this.$nextTick(() => {
        this.checkInventoryAlertsCount();
        this.calculateRecommendedThresholds(); // 数据变化后重新计算推荐阈值
      });
    },
    saveAllocationData() {
      localStorage.setItem('productAllocationData', JSON.stringify(this.originalTableData))
      // 触发事件，以便其他实例（如果有）也能感知到变化
      window.dispatchEvent(new CustomEvent('storageUpdated', { detail: { key: 'productAllocationData' } }));

      // 保存数据后检查库存预警数量，但不显示弹窗
      this.$nextTick(() => {
        this.checkInventoryAlertsCount();
      });
    },

    // 检查预警数量，不显示弹窗
    checkInventoryAlertsCount() {
      // 重置预警信息
      this.inventoryAlertDialog.alerts = [];

      // 如果没有数据，则不进行检查
      if (!this.originalTableData || this.originalTableData.length === 0) {
        this.inventoryAlertCount = 0;
        // 保存预警数量到localStorage
        localStorage.setItem('inventoryAlertCount', '0');
        return;
      }

      // 按仓库分组商品
      const warehouseGroups = this.groupByWarehouse(this.originalTableData);

      // 检查每个仓库的库存情况
      for (const warehouseId in warehouseGroups) {
        const warehouseProducts = warehouseGroups[warehouseId];
        const warehouseName = this.getWarehouseName(warehouseId);

        // 检查库存为0的商品
        const zeroStockProducts = warehouseProducts.filter(
          item => item.currentQuantity === 0 &&
                 (item.status === '库存中' || item.status === '部分出库' || item.status === '全部出库')
        );

        if (zeroStockProducts.length > 0) {
          this.inventoryAlertDialog.alerts.push({
            type: 'error',
            title: `${warehouseName}有${zeroStockProducts.length}种商品库存为零`,
            description: `商品: ${zeroStockProducts.map(p => p.productName).join(', ')}`,
            warehouseId,
            products: zeroStockProducts
          });
        }

        // 检查低库存商品
        const lowStockProducts = warehouseProducts.filter(
          item => item.currentQuantity > 0 &&
                 item.currentQuantity <= this.inventoryAlertConfig.lowStockThreshold
        );

        if (lowStockProducts.length > 0) {
          this.inventoryAlertDialog.alerts.push({
            type: 'warning',
            title: `${warehouseName}有${lowStockProducts.length}种商品库存不足`,
            description: `商品: ${lowStockProducts.map(p => p.productName).join(', ')}`,
            warehouseId,
            products: lowStockProducts
          });
        }

        // 检查高库存商品
        const highStockProducts = warehouseProducts.filter(
          item => item.currentQuantity >= this.inventoryAlertConfig.highStockThreshold
        );

        if (highStockProducts.length > 0) {
          this.inventoryAlertDialog.alerts.push({
            type: 'info',
            title: `${warehouseName}有${highStockProducts.length}种商品库存过多`,
            description: `商品: ${highStockProducts.map(p => p.productName).join(', ')}`,
            warehouseId,
            products: highStockProducts
          });
        }

        // 检查库存趋势（如果有历史数据）
        this.checkInventoryTrends(warehouseProducts, warehouseName, warehouseId);
      }

      // 更新预警数量
      this.inventoryAlertCount = this.inventoryAlertDialog.alerts.length;
      // 保存预警数量到localStorage
      localStorage.setItem('inventoryAlertCount', this.inventoryAlertCount.toString());
      this.lastAlertCheckTime = new Date();
    },

    // 新增方法：显示库存预警弹窗
    showInventoryAlerts() {
      this.isCheckingAlerts = true;

      // 重新检查库存预警
      this.checkInventoryAlertsCount();

      // 如果有预警，则显示预警弹窗并生成建议
      if (this.inventoryAlertDialog.alerts.length > 0) {
        this.generateSmartSuggestion();
        this.inventoryAlertDialog.visible = true;
      } else {
        // 如果没有预警，显示提示信息
        this.$message({
          message: '当前没有库存预警',
          type: 'success'
        });
      }

      this.isCheckingAlerts = false;
    },

    // 保留原有的 checkInventoryAlerts 方法，但不再直接调用它
    // checkInventoryAlerts() {
    //   // 重置预警信息
    //   this.inventoryAlertDialog.alerts = [];

    //   // 如果没有数据，则不进行检查
    //   if (!this.originalTableData || this.originalTableData.length === 0) {
    //     return;
    //   }

    //   // 按仓库分组商品
    //   const warehouseGroups = this.groupByWarehouse(this.originalTableData);

    //   // 检查每个仓库的库存情况
    //   for (const warehouseId in warehouseGroups) {
    //     const warehouseProducts = warehouseGroups[warehouseId];
    //     const warehouseName = this.getWarehouseName(warehouseId);

    //     // 检查低库存商品
    //     const lowStockProducts = warehouseProducts.filter(
    //       item => item.currentQuantity > 0 &&
    //              item.currentQuantity <= this.inventoryAlertConfig.lowStockThreshold
    //     );

    //     if (lowStockProducts.length > 0) {
    //       this.inventoryAlertDialog.alerts.push({
    //         type: 'warning',
    //         title: `${warehouseName}有${lowStockProducts.length}种商品库存不足`,
    //         description: `商品: ${lowStockProducts.map(p => p.productName).join(', ')}`,
    //         warehouseId,
    //         products: lowStockProducts
    //       });
    //     }

    //     // 检查高库存商品
    //     const highStockProducts = warehouseProducts.filter(
    //       item => item.currentQuantity >= this.inventoryAlertConfig.highStockThreshold
    //     );

    //     if (highStockProducts.length > 0) {
    //       this.inventoryAlertDialog.alerts.push({
    //         type: 'info',
    //         title: `${warehouseName}有${highStockProducts.length}种商品库存过多`,
    //         description: `商品: ${highStockProducts.map(p => p.productName).join(', ')}`,
    //         warehouseId,
    //         products: highStockProducts
    //       });
    //     }

    //     // 检查库存趋势（如果有历史数据）
    //     this.checkInventoryTrends(warehouseProducts, warehouseName, warehouseId);
    //   }

    //   // 更新预警数量
    //   this.inventoryAlertCount = this.inventoryAlertDialog.alerts.length;
    // },

    handleQuery() {
      let filteredData = [...this.originalTableData]

      if (this.queryParams.productName) {
        filteredData = filteredData.filter(item => item.productName && item.productName.includes(this.queryParams.productName))
      }
      if (this.queryParams.purchaseOrderNo) {
        filteredData = filteredData.filter(item => item.purchaseOrderNo && item.purchaseOrderNo.includes(this.queryParams.purchaseOrderNo))
      }
      if (this.queryParams.warehouseId) {
        filteredData = filteredData.filter(item => item.warehouseId === this.queryParams.warehouseId)
      }
      if (this.queryParams.status) {
        filteredData = filteredData.filter(item => item.status === this.queryParams.status)
      }
      // 按入库时间倒序排列，新的在前
      filteredData.sort((a, b) => new Date(b.storageTimestamp) - new Date(a.storageTimestamp));


      this.pagination.total = filteredData.length
      this.pagination.currentPage = 1 // 重置到第一页
      this.updateTableData()
    },
    resetQuery() {
      this.queryParams = {
        productName: '',
        purchaseOrderNo: '',
        warehouseId: '',
        status: '',
      }
      this.handleQuery()
    },
    updateTableData() {
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize
      const end = start + this.pagination.pageSize
      this.tableData = this.originalTableData.slice(start, end) // 注意：这里应该用筛选和排序后的数据
       // 修正：应该对筛选和排序后的数据进行分页
      let dataToPaginate = [...this.originalTableData]; // Start with a copy
      // Apply filters (example, assuming filters are applied before pagination)
      if (this.queryParams.productName) {
        dataToPaginate = dataToPaginate.filter(item => item.productName && item.productName.includes(this.queryParams.productName));
      }
      if (this.queryParams.purchaseOrderNo) {
        dataToPaginate = dataToPaginate.filter(item => item.purchaseOrderNo && item.purchaseOrderNo.includes(this.queryParams.purchaseOrderNo));
      }
      if (this.queryParams.warehouseId) {
        dataToPaginate = dataToPaginate.filter(item => item.warehouseId === this.queryParams.warehouseId);
      }
      if (this.queryParams.status) {
        dataToPaginate = dataToPaginate.filter(item => item.status === this.queryParams.status);
      }
      dataToPaginate.sort((a, b) => new Date(b.storageTimestamp) - new Date(a.storageTimestamp));

      this.pagination.total = dataToPaginate.length; // Update total based on filtered data
      this.tableData = dataToPaginate.slice(start, end);
    },
    handleCurrentChange(page) {
      this.pagination.currentPage = page
      this.updateTableData()
    },
    handleSizeChange(size) {
      this.pagination.pageSize = size
      this.pagination.currentPage = 1
      this.updateTableData()
    },
    resetDispatchForm() {
        if(this.$refs.dispatchForm) {
            this.$refs.dispatchForm.resetFields();
        }
        this.dispatchDialog.form = { quantity: 1, destination: '' };
    },
    handleDispatch(row) {
      this.dispatchDialog.currentRow = row
      this.dispatchDialog.form.quantity = 1; // Reset quantity
      this.dispatchDialog.form.destination = ''; // Reset destination
      this.dispatchDialog.visible = true
    },
    saveLogisticsData(newEntry) {
      const data = localStorage.getItem('logisticsCenterData');
      const logistics = data ? JSON.parse(data) : [];
      logistics.push(newEntry);
      localStorage.setItem('logisticsCenterData', JSON.stringify(logistics));
      // 触发事件，以便物流中心页面感知到变化
      window.dispatchEvent(new CustomEvent('storageUpdated', { detail: { key: 'logisticsCenterData' } }));
    },

    generateLogisticsId(typePrefix = 'LOG') {
      return `${typePrefix}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    },

    confirmDispatch() {
      this.$refs.dispatchForm.validate(valid => {
        if (valid) {
          const item = this.originalTableData.find(i => i.id === this.dispatchDialog.currentRow.id)
          if (item) {
            if (this.dispatchDialog.form.quantity > item.currentQuantity) {
              this.$message.error('出库数量不能大于当前数量');
              return;
            }

            const dispatchedQuantity = this.dispatchDialog.form.quantity;
            item.currentQuantity -= dispatchedQuantity;
            if (item.currentQuantity === 0) {
              item.status = '全部出库'
            } else {
              item.status = '部分出库'
            }

            // 创建物流记录
            const logisticsEntry = {
              logisticsId: this.generateLogisticsId('DISPATCH'),
              operationType: '出库',
              productName: item.productName,
              quantity: dispatchedQuantity,
              orderNo: item.purchaseOrderNo, // 使用采购单号作为关联
              sourceWarehouseLabel: item.warehouseLabel,
              destination: this.dispatchDialog.form.destination,
              timestamp: new Date().toLocaleString('zh-CN', { hour12: false }),
              status: '运输中', // 初始状态
              relatedAllocationId: item.id,
            };
            this.saveLogisticsData(logisticsEntry);

            this.saveAllocationData()
            this.handleQuery() // Refresh table
            this.$message.success('出库成功')
            this.dispatchDialog.visible = false
          }
        }
      })
    },
    resetTransferForm() {
        if(this.$refs.transferForm) {
            this.$refs.transferForm.resetFields();
        }
       this.transferDialog.form = { quantity: 1, targetWarehouseId: '' };
    },
    handleTransfer(row) {
      this.transferDialog.currentRow = row;
      this.transferDialog.form.quantity = 1;
      this.transferDialog.form.targetWarehouseId = '';
      this.transferDialog.visible = true;
    },
    confirmTransfer() {
      this.$refs.transferForm.validate(valid => {
        if (valid) {
          const sourceItem = this.originalTableData.find(i => i.id === this.transferDialog.currentRow.id);
          if (!sourceItem) return;

          const quantityToTransfer = this.transferDialog.form.quantity;
          if (quantityToTransfer > sourceItem.currentQuantity) {
            this.$message.error('调拨数量不能大于当前数量');
            return;
          }

          const targetWarehouse = this.warehouseOptions.find(wh => wh.value === this.transferDialog.form.targetWarehouseId);
          if (!targetWarehouse) {
             this.$message.error('无效的目标仓库');
             return;
          }

          // 1. Update source item
          sourceItem.currentQuantity -= quantityToTransfer;
          if (sourceItem.currentQuantity === 0) {
            sourceItem.status = '已调拨';
          } else {
            // 如果原本是库存中，部分调拨后，可以认为是“部分出库”的一种，或者自定义“部分调拨”
            // 为保持一致性，如果不是全部调拨完，可以标记为“部分出库”或“库存中”
            // 这里我们假设如果还有剩余，则状态变更为“部分出库”或保持“库存中”
            // 如果希望更细致，可以新增“部分调拨”状态
             sourceItem.status = sourceItem.initialQuantity > sourceItem.currentQuantity ? '部分出库' : '库存中';
             if (sourceItem.currentQuantity < sourceItem.initialQuantity && sourceItem.currentQuantity > 0) {
                sourceItem.status = '部分出库'; // 或者 '部分调拨'
             }
          }

          // 2. Create new entry for target warehouse (this is allocation data, not logistics)
          const newAllocationEntry = {
            ...sourceItem,
            id: `ALLOC-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
            warehouseId: targetWarehouse.value,
            warehouseLabel: targetWarehouse.label,
            initialQuantity: quantityToTransfer,
            currentQuantity: quantityToTransfer,
            storageTimestamp: new Date().toLocaleString('zh-CN', { hour12: false }),
            status: '库存中',
          };
          this.originalTableData.push(newAllocationEntry);

          // 创建物流记录
          const logisticsEntry = {
            logisticsId: this.generateLogisticsId('TRANSFER'),
            operationType: '调拨',
            productName: sourceItem.productName,
            quantity: quantityToTransfer,
            orderNo: `T-${sourceItem.id.slice(-6)}-${targetWarehouse.value.slice(-3)}`, // 自定义调拨单号
            sourceWarehouseLabel: sourceItem.warehouseLabel,
            destination: targetWarehouse.label,
            timestamp: new Date().toLocaleString('zh-CN', { hour12: false }),
            status: '运输中', // 初始状态
            relatedAllocationId: sourceItem.id, // 关联原库存ID
          };
          this.saveLogisticsData(logisticsEntry);

          this.saveAllocationData();
          this.handleQuery();
          this.$message.success('调拨成功');
          this.transferDialog.visible = false;
        }
      });
    },
    handleReturn(row) {
      this.returnDialog.currentRow = row;
      this.returnDialog.form.reason = '';
      this.returnDialog.visible = true;
    },

    confirmReturn() {
      this.$refs.returnForm.validate(valid => {
        if (valid) {
          const item = this.originalTableData.find(i => i.id === this.returnDialog.currentRow.id);
          if (item) {
            // 更新商品状态为已退货
            item.status = '已退货';

            // 创建物流记录
            const logisticsEntry = {
              logisticsId: this.generateLogisticsId('RETURN'),
              operationType: '退货',
              productName: item.productName,
              quantity: item.currentQuantity, // 全部退货
              orderNo: item.purchaseOrderNo,
              sourceWarehouseLabel: item.warehouseLabel,
              destination: '供应商',
              timestamp: new Date().toLocaleString('zh-CN', { hour12: false }),
              status: '退货中',
              relatedAllocationId: item.id,
              remarks: this.returnDialog.form.reason,
            };
            this.saveLogisticsData(logisticsEntry);

            this.saveAllocationData();
            this.handleQuery(); // 刷新表格
            this.$message.success('退货操作成功');
            this.returnDialog.visible = false;
          }
        }
      });
    },
    handleDetail(row) {
      this.detailDialog.currentRow = row;
      this.detailDialog.visible = true;
    },

    // 新增方法：检查库存预警
    checkInventoryAlerts() {
      // 重置预警信息
      this.inventoryAlertDialog.alerts = [];

      // 如果没有数据，则不进行检查
      if (!this.originalTableData || this.originalTableData.length === 0) {
        return;
      }

      // 按仓库分组商品
      const warehouseGroups = this.groupByWarehouse(this.originalTableData);

      // 检查每个仓库的库存情况
      for (const warehouseId in warehouseGroups) {
        const warehouseProducts = warehouseGroups[warehouseId];
        const warehouseName = this.getWarehouseName(warehouseId);

        // 检查低库存商品
        const lowStockProducts = warehouseProducts.filter(
          item => item.currentQuantity > 0 &&
                 item.currentQuantity <= this.inventoryAlertConfig.lowStockThreshold
        );

        if (lowStockProducts.length > 0) {
          this.inventoryAlertDialog.alerts.push({
            type: 'warning',
            title: `${warehouseName}有${lowStockProducts.length}种商品库存不足`,
            description: `商品: ${lowStockProducts.map(p => p.productName).join(', ')}`,
            warehouseId,
            products: lowStockProducts
          });
        }

        // 检查高库存商品
        const highStockProducts = warehouseProducts.filter(
          item => item.currentQuantity >= this.inventoryAlertConfig.highStockThreshold
        );

        if (highStockProducts.length > 0) {
          this.inventoryAlertDialog.alerts.push({
            type: 'info',
            title: `${warehouseName}有${highStockProducts.length}种商品库存过多`,
            description: `商品: ${highStockProducts.map(p => p.productName).join(', ')}`,
            warehouseId,
            products: highStockProducts
          });
        }

        // 检查库存趋势（如果有历史数据）
        this.checkInventoryTrends(warehouseProducts, warehouseName, warehouseId);
      }

      // 如果有预警，则显示预警弹窗并生成建议
      if (this.inventoryAlertDialog.alerts.length > 0) {
        this.generateSmartSuggestion();
        this.inventoryAlertDialog.visible = true;
      }
    },

    // 按仓库分组商品
    groupByWarehouse(products) {
      const groups = {};

      products.forEach(product => {
        if (!groups[product.warehouseId]) {
          groups[product.warehouseId] = [];
        }
        groups[product.warehouseId].push(product);
      });

      return groups;
    },

    // 获取仓库名称
    getWarehouseName(warehouseId) {
      const warehouse = this.warehouseOptions.find(w => w.value === warehouseId);
      return warehouse ? warehouse.label : '未知仓库';
    },

    // 检查库存趋势
    checkInventoryTrends(products, warehouseName, warehouseId) {
      // 获取历史出库记录（这里模拟，实际应从API或localStorage获取）
      const logisticsData = this.getHistoryLogisticsData();

      // 对每个产品分析消耗趋势
      products.forEach(product => {
        // 只分析当前库存中的商品
        if (product.status !== '库存中' && product.status !== '部分出库') {
          return;
        }

        // 获取该产品的历史出库记录
        const productHistory = logisticsData.filter(
          log => log.productName === product.productName &&
                 log.operationType === '出库' &&
                 log.sourceWarehouseLabel === product.warehouseLabel
        );

        // 如果有足够的历史数据，计算平均消耗速率
        if (productHistory.length >= 2) {
          const consumptionRate = this.calculateConsumptionRate(productHistory, product);

          // 预测库存耗尽时间
          const daysRemaining = Math.floor(product.currentQuantity / consumptionRate);

          // 如果预计在7天内库存耗尽，添加预警
          if (daysRemaining <= 7 && daysRemaining > 0) {
            this.inventoryAlertDialog.alerts.push({
              type: 'error',
              title: `${product.productName}库存即将耗尽`,
              description: `预计在${daysRemaining}天后库存将耗尽，建议及时补货`,
              warehouseId,
              products: [product],
              consumptionRate,
              daysRemaining
            });
          }
        }
      });
    },

    // 获取历史物流数据
    getHistoryLogisticsData() {
      const data = localStorage.getItem('logisticsCenterData');
      return data ? JSON.parse(data) : [];
    },

    // 计算消耗速率（每天平均消耗量）
    calculateConsumptionRate(history, product) {
      // 按时间排序
      history.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));

      // 计算总消耗量
      const totalConsumption = history.reduce((sum, record) => sum + record.quantity, 0);

      // 计算时间跨度（天）
      const firstDate = new Date(history[0].timestamp);
      const lastDate = new Date(history[history.length - 1].timestamp);
      const daySpan = Math.max(1, Math.ceil((lastDate - firstDate) / (1000 * 60 * 60 * 24)));

      // 计算每天平均消耗量
      return totalConsumption / daySpan;
    },

    // 生成智能建议
    generateSmartSuggestion() {
      // 根据预警类型生成不同的建议
      const lowStockAlerts = this.inventoryAlertDialog.alerts.filter(a => a.type === 'warning' || a.type === 'error');
      const highStockAlerts = this.inventoryAlertDialog.alerts.filter(a => a.type === 'info');

      if (lowStockAlerts.length > 0 && highStockAlerts.length > 0) {
        // 既有低库存又有高库存，建议调拨
        const sourceWarehouse = highStockAlerts[0].warehouseId;
        const targetWarehouse = lowStockAlerts[0].warehouseId;

        if (sourceWarehouse !== targetWarehouse) {
          this.inventoryAlertDialog.suggestion = `建议将${this.getWarehouseName(sourceWarehouse)}的过量库存调拨至${this.getWarehouseName(targetWarehouse)}，以平衡各仓库库存。`;
          this.inventoryAlertDialog.actionText = '执行调拨';
          this.inventoryAlertDialog.actionType = 'transfer';
          this.inventoryAlertDialog.targetWarehouse = targetWarehouse;
          this.inventoryAlertDialog.sourceWarehouse = sourceWarehouse;
        } else {
          this.inventoryAlertDialog.suggestion = '建议及时补充低库存商品，并考虑促销高库存商品。';
          this.inventoryAlertDialog.actionText = '查看详情';
          this.inventoryAlertDialog.actionType = 'view';
        }
      } else if (lowStockAlerts.length > 0) {
        // 只有低库存，建议补货
        this.inventoryAlertDialog.suggestion = '建议及时补充库存不足的商品，避免影响正常业务。';
        this.inventoryAlertDialog.actionText = '创建采购单';
        this.inventoryAlertDialog.actionType = 'purchase';
      } else if (highStockAlerts.length > 0) {
        // 只有高库存，建议促销或调整
        this.inventoryAlertDialog.suggestion = '库存过高可能导致资金积压和仓储压力，建议适当促销或调整采购计划。';
        this.inventoryAlertDialog.actionText = '查看详情';
        this.inventoryAlertDialog.actionType = 'view';
      }
    },

    // 处理预警操作
    handleAlertAction() {
      switch (this.inventoryAlertDialog.actionType) {
        case 'transfer':
          // 跳转到调拨页面或自动填充调拨表单
          this.prepareTransfer();
          break;
        case 'purchase':
          // 跳转到采购页面
          this.navigateToPurchase();
          break;
        case 'view':
        default:
          // 关闭弹窗
          this.inventoryAlertDialog.visible = false;
          break;
      }
    },

    // 准备调拨操作
    prepareTransfer() {
      // 获取建议调拨的商品
      const sourceWarehouse = this.inventoryAlertDialog.sourceWarehouse;
      const targetWarehouse = this.inventoryAlertDialog.targetWarehouse;

      // 找到高库存的商品和低库存的商品
      const highStockAlerts = this.inventoryAlertDialog.alerts.filter(a => a.type === 'info' && a.warehouseId === sourceWarehouse);
      const lowStockAlerts = this.inventoryAlertDialog.alerts.filter(a => (a.type === 'warning' || a.type === 'error') && a.warehouseId === targetWarehouse);

      if (highStockAlerts.length > 0 && lowStockAlerts.length > 0) {
        // 选择第一个高库存商品进行调拨
        const productToTransfer = highStockAlerts[0].products[0];

        // 关闭预警弹窗
        this.inventoryAlertDialog.visible = false;

        // 打开调拨弹窗并预填数据
        this.transferDialog.currentRow = productToTransfer;
        this.transferDialog.form.quantity = Math.min(
          productToTransfer.currentQuantity - this.inventoryAlertConfig.lowStockThreshold,
          this.inventoryAlertConfig.highStockThreshold - this.inventoryAlertConfig.lowStockThreshold
        );
        this.transferDialog.form.targetWarehouseId = targetWarehouse;
        this.transferDialog.visible = true;
      }
    },

    // 跳转到采购页面
    navigateToPurchase() {
      this.inventoryAlertDialog.visible = false;
      // 跳转到采购页面
      this.$router.push('/vab/tree');
    },

    // 新增方法：计算推荐的库存阈值
    calculateRecommendedThresholds() {
      if (!this.originalTableData || this.originalTableData.length === 0) {
        this.recommendedLowStockThreshold = 10; // 默认值
        this.recommendedHighStockThreshold = 1000; // 默认值
        return;
      }

      const consumptionRates = [];
      const today = new Date();

      this.originalTableData.forEach(item => {
        if (item.initialQuantity > 0 && item.storageTimestamp) {
          const storageDate = new Date(item.storageTimestamp);
          // 计算实际在库天数，避免未来时间戳导致负数或零天数问题
          let daysInStock = (today.getTime() - storageDate.getTime()) / (1000 * 60 * 60 * 24);
          daysInStock = Math.max(1, daysInStock); // 确保至少为1天，防止除以零

          const consumedQuantity = item.initialQuantity - item.currentQuantity;

          if (consumedQuantity > 0) { // 仅当有消耗时才计算比率
            const dailyRate = consumedQuantity / daysInStock;
            consumptionRates.push(dailyRate);
          }
        }
      });

      if (consumptionRates.length === 0) {
        // 如果无法计算消耗率 (例如所有商品都是新入库或无消耗记录)
        // 则基于当前库存量的百分位数进行推荐
        const quantities = this.originalTableData
          .map(item => item.currentQuantity)
          .filter(qty => typeof qty === 'number' && qty > 0) // 确保是有效数字
          .sort((a, b) => a - b);

        if (quantities.length > 0) {
          this.recommendedLowStockThreshold = Math.max(5, Math.round(quantities[Math.floor(quantities.length * 0.1)] || 5));
          this.recommendedHighStockThreshold = Math.max(50, Math.round(quantities[Math.floor(quantities.length * 0.9)] || 500));
        } else {
          this.recommendedLowStockThreshold = 10;
          this.recommendedHighStockThreshold = 1000;
        }
      } else {
        const averageDailyConsumption = consumptionRates.reduce((sum, rate) => sum + rate, 0) / consumptionRates.length;

        const safetyDaysForLowStock = this.inventoryAlertConfig.averageConsumptionPeriod || 7;
        const safetyDaysForHighStock = 60; // 例如，目标是持有60天的库存量作为上限参考

        this.recommendedLowStockThreshold = Math.max(1, Math.round(averageDailyConsumption * safetyDaysForLowStock));
        this.recommendedHighStockThreshold = Math.max(
          this.recommendedLowStockThreshold + 10, // 确保高阈值至少比低阈值大10
          Math.round(averageDailyConsumption * safetyDaysForHighStock)
        );
      }

      // 确保高阈值总是大于低阈值，并设置合理的最小高阈值
      if (this.recommendedHighStockThreshold <= this.recommendedLowStockThreshold) {
        this.recommendedHighStockThreshold = this.recommendedLowStockThreshold * 5 > 50 ? this.recommendedLowStockThreshold * 5 : 50;
      }
      if (this.recommendedHighStockThreshold < 50) {
         this.recommendedHighStockThreshold = 50;
      }
       // 确保低阈值不为0
      if (this.recommendedLowStockThreshold < 1) {
        this.recommendedLowStockThreshold = 1;
      }
    },

    // 新增方法：应用新的阈值并重新计算预警
    applyAndRecalculateAlerts() {
      // 阈值通过 v-model 已经绑定更新
      this.$nextTick(() => {
        this.checkInventoryAlertsCount(); // 使用新的阈值重新检查预警
        this.$message.success('阈值已更新，库存预警已重新计算！');
      });
    },

    // 新增方法：手动触发重新计算推荐阈值
    recalculateRecommendations() {
      this.calculateRecommendedThresholds();
      this.$message.success('建议阈值已重新计算！');
    },
  }
}
</script>

<style lang="scss" scoped>
.product-allocation-container {
  padding: 20px;
}
.filter-container {
  margin-bottom: 20px;
}
.table-container {
  // styles for table container
}
.dialog-footer {
  text-align: right;
}
.inventory-alert-item {
  margin-bottom: 10px;
}

.inventory-alert-suggestion {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border-left: 4px solid #409EFF;
}

.inventory-alert-suggestion h4 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #409EFF;
}

.no-alerts-message {
  text-align: center;
  padding: 20px;
}

.no-alerts-message i {
  font-size: 48px;
  color: #67C23A;
  margin-bottom: 10px;
}

.inventory-alert-btn {
  position: relative;
}

.alert-badge {
  position: absolute;
  top: -8px;
  right: -8px;
}
</style>
